# _*_ encoding: utf-8 _*_
import optparse


class Route:
    def __init__(self):
        self.depart = {}
        self.arrival = {}
        pass

    def get_depart(self, data):
        v_id, v_depart = data[0], data[1]
        self.depart.setdefault(v_id, v_depart)
        self.arrival[v_id] = v_depart

    def process(self, data):
        self.get_depart(data)

    def write(self, filename):
        buf = []
        with open(filename, "wb") as f:
            buf.append("vehicleId, departTime, arrivalTime\n")
            for key, value in sorted(self.depart.iteritems(), key= lambda d:d[1], reverse=False):
                buf.append("{0},{1},{2}\n".format(key, value, self.arrival[key]))
            f.writelines(buf)


def parse_line(line):
    elems = line.strip().split(',')
    elems[1] = int(float(elems[1]))
    return elems


def read_file(filename, handler):
    assert isinstance(handler, Route)
    with open(filename, "rb") as f:
        for line in f:
            handler.process(parse_line(line))


def get_options(args=None):
    optparser = optparse.OptionParser()
    optparser.add_option("-c", "--csv-file", dest="csv", help="the input gps csv file")
    optparser.add_option("-d", "--depart-file", dest="depart", help="the output route file")
    (options, args) = optparser.parse_args(args=args)
    if options.csv is None or options.depart is None:
        optparser.print_help()
        exit(1)
    return options


def main(options=None):
    route = Route()
    read_file(options.csv, route)
    route.write(options.depart)

if __name__ == '__main__':
    main(get_options())